#include "client.h"
#include "log.h"


Client::Client() {
	game = new Game();
	r = new Renderer();
	game->renderer = r;
};

void Client::put(char *s) {
	SDLNet_TCP_Send(_server.sd, (void*)s, sizeof(char)*strlen(s));
};

// Main client thread
int Client::main_client_thread() {
  // do we need SDLNet_Init() ?
  _server.host = "127.0.0.1";
  _server.port = 6661;
  _client_identifier = 123; // will be changed accordign to server first response
  // resolve host
  if (SDLNet_ResolveHost(&_server.ip, _server.host, _server.port) < 0)  {
    *lg << error << "SDLNet_ResolveHost: " <<  SDLNet_GetError() << fl;
    return -1;
	} else {
     // host resolved
     *lg << info << "Host resolved" << fl;

     Uint32 ipaddr; 
     ipaddr=SDL_SwapBE32(_server.ip.host);

    *lg << info << "Host's IP Address : " <<	(ipaddr>>24) << '.' << ((ipaddr>>16)&0xff) << '.' << ((ipaddr>>8)&0xff) << '.' << (ipaddr&0xff) << fl; 

  }

  // open connection
  if (!(_server.sd = SDLNet_TCP_Open(&_server.ip)))	{
    *lg << error <<  "SDLNet_TCP_Open: " << SDLNet_GetError() << fl;
    return -1;
  } else {
    // connection opened
    // send something
    int len = strlen("Hello");
    if (SDLNet_TCP_Send(_server.sd, (void*)"Hello", len) < len)
		{
			*lg << error << "SDLNet_TCP_Send: " << SDLNet_GetError() << fl;
			return -1;
		} else {
      *lg << info << "Client::Got connection to the server" << fl;
    }
  }
   
  int len;
  char iden[10]; 
  // Wait for ID
  while(1) {
    len=SDLNet_TCP_Recv(_server.sd, iden, 10);
  	if(len) {
      *lg << "Client now known as: " << iden << fl;
    break;
    }
  }
  _client_identifier = atoi(iden);

	// First hardcoded command, WILL CHANGE

	SDLNet_TCP_Send(_server.sd, (void*)"!CNPlayer,N14,Amstodenflojch", strlen("!CNPlayer,N14,Amstodenflojch"));

  
  char message[1024]; 
  while(1) {
    // read the buffer from server
    len=SDLNet_TCP_Recv(_server.sd, message, 1024);
    if(len) { 
      *lg << "Client::Resp from server " << '[' << len << ']' << ' ' << message << fl; 

		if ((message[0] == '!') && (message[1] == 'S')) {
			*lg << "Client::Resp recv'd cmd:" << message <<fl;
      char data[10];
      itoa(_client_identifier, data, 10);
			game->parse_proto(message+1, strlen(message+1), data);
		};

    } else { 
      *lg << error << "SDLNet_TCP_Recv: " << SDLNet_GetError() << lg; 
    }
    if(memcmp(message, "0", 1)==0) {
      // server stopping, stop listening
	  *lg << "Client TCP Close" << fl;
      SDLNet_TCP_Close(_server.sd);
      break;
    }
    //SDLNet_TCP_Send(_server.sd, (void*)"test", 4);

  }
}
